package com.xyhuo.leetcode.june;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * 179. 最大数
 * https://leetcode.cn/problems/largest-number/
 */
public class LargestNumber {

    public static void main(String[] args) {
        LargestNumber ln = new LargestNumber();
        int[] nums = {432, 43243};
        ln.largestNumber(nums);
    }

    public String largestNumber(int[] nums) {

        List<String> numStrList = new ArrayList<>();
        for (int num : nums) {
            numStrList.add(String.valueOf(num));
        }
        numStrList.sort(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                if (o1.equals(o2)) {
                    return 0;
                }
                char[] o1CharArray = o1.toCharArray();
                char[] o2CharArray = o2.toCharArray();
                int leftIndex = 0, rightIndex = 0, leftCount = 0, rightCount = 0;
                while (true) {
                    if (leftCount > 1 && rightCount > 1) {
                        return 0;
                    }
                    if (leftIndex >= o1.length()) {
                        leftIndex = 0;
                        leftCount++;
                    }
                    if (rightIndex >= o2.length()) {
                        rightIndex = 0;
                        rightCount++;
                    }
                    if (o1CharArray[leftIndex] == o2CharArray[rightIndex]) {
                        leftIndex++;
                        rightIndex++;
                        continue;
                    }
                    return o2CharArray[rightIndex] - o1CharArray[leftIndex];
                }
            }
        });
        StringBuilder sb = new StringBuilder();
        for (String item : numStrList) {
            sb.append(item);
        }

        String result = sb.toString();
        if (result.startsWith("0")) {
            return "0";
        }
        return result;
    }

}
